package z.practice_db;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author yi qiang
 * @date 2021/6/1 17:50
 */
public class DbUtil {
    public static <T> Object query(Class<T> clazz) throws Exception {
        String sql = "SELECT * FROM Course";
        Properties properties = new Properties();
        InputStream inputStream = DbUtil.class.getResourceAsStream("/z/practice_db/db.properties");
        properties.load(inputStream);
        ResultSet resultSet;
        try (Connection connection = DriverManager.getConnection(properties.getProperty("url")
                , properties.getProperty("username")
                , properties.getProperty("password"));
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            resultSet = preparedStatement.executeQuery();
            List<T> tList = new ArrayList<>();
            while (resultSet.next()) {
                T t = clazz.newInstance();
                Field[] declaredFields = clazz.getDeclaredFields();
                for (Field field : declaredFields) {
                    String fieldName = field.getName();
                    String filedResult = resultSet.getString(fieldName);
                    Method method = clazz.getMethod("set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1)
                            , String.class);
                    method.invoke(t, filedResult);
                }
                tList.add(t);
            }
            return tList;
        }
    }

    public static void main(String[] args) throws Exception {
        Object query = query(Course.class);
        System.out.println(query);
    }

    public static class Course {
        private String c_id;
        private String c_name;

        public String getC_name() {
            return c_name;
        }

        public void setC_name(String c_name) {
            this.c_name = c_name;
        }

        public String getC_id() {
            return c_id;
        }

        public void setC_id(String c_id) {
            this.c_id = c_id;
        }

        @Override
        public String toString() {
            return "Course{" +
                    "c_id='" + c_id + '\'' +
                    ", c_name='" + c_name + '\'' +
                    '}';
        }
    }
}
